package com.itwxz.games.utils;

import cn.hutool.core.util.RandomUtil;
import com.itwxz.common.core.redis.RedisCache;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class CreateIdUtils {
    private final RedisCache redisCache;

    @Getter
    private final String uKeyPrefix = "undercover:room:";

    @Getter
    private final String wKeyPrefix = "werewolf:room:";

    public Long getUCRoomId() {
        return createRoomId(uKeyPrefix);
    }


    public Long getWCRoomId() {
       return createRoomId(wKeyPrefix);
    }

    /**
     * 智能生成唯一房间号：
     * 4位开始，重复3次变5位，再重复3次变6位（最多6位）
     */
    public Long createRoomId(String keyPrefix) {
        int length = 4;
        int retryCount = 0;

        while (true) {
            String roomId = RandomUtil.randomNumbers(length);
            String key = keyPrefix + roomId;

            if (!redisCache.hasKey(key)) {
                return Long.parseLong(roomId);
            }

            retryCount++;
            if (retryCount >= 3) {
                retryCount = 0;
                length = Math.min(length + 1, 6);
            }
        }
    }
}
